<template>
  <div
    id="createAdvertising"
    class="dialog animated"
    :class="open? 'fadeIn':'fadeOut'"
    v-show="show"
    :style="{visibility: (visible?'visible':'hidden')}"
  >
    <div class="panel animated" :class="open? 'zoomIn':''">
      <div class="title">
        {{title}}
        <div class="close" @click="cancel()"></div>
      </div>
      <div style="min-height: 6rem;overflow: hidden;">
        <div style="float:left;width:8rem;">
          <span class="launch_text">设置区域</span>
          <el-form :model="advertisingData" ref="advertisingData" label-width="132px">
            <el-form-item label="广告名称" :rules="[
      { required: true, message: ''}]">
              <el-input
                ref="adName"
                style="width:80%"
                clearable
                :disabled="isLook"
                v-model="advertisingData.adName"
                maxlength="20"
                placeholder="请输入广告名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="投放区域" :rules="[
      { required: true, message: ''}]">
              <el-select
                ref="adRegionMode"
                style="width:80%"
                v-if="true"
                clearable
                :disabled="isLook"
                v-model="advertisingData.adRegionMode"
                placeholder="请选择投放区域"
                @change="handleCheckedChange"
              >
                <el-option
                  v-for="item in adRegionModeList"
                  :key="item.valueId"
                  :label="item.valueName"
                  :value="item.valueIndex"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="投放位置" :rules="[
      { required: true, message: ''}]">
              <el-select
                v-if="advertisingData.adRegionMode != 2"
                ref="adPosition"
                style="width:80%"
                clearable
                :disabled="isLook"
                v-model="advertisingData.adPositionId"
                placeholder="请选择投放位置"
              >
                <el-option
                  v-for="item in adPositionList"
                  :key="item.valueId"
                  :label="item.valueName"
                  :value="item.valueId"
                ></el-option>
              </el-select>
              <div style="width:80%" v-else>
                <el-select
                  ref="adTerminal"
                  style="width:48%"
                  :disabled="isLook"
                  v-model="advertisingData.adTerminalMode"
                  placeholder="请选择投放客户端"
                >
                  <el-option
                    v-for="item in adTerminalList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-select
                  ref="adPosition"
                  style="width:50%"
                  clearable
                  :disabled="isLook"
                  v-model="advertisingData.adPositionId"
                  placeholder="请选择投放位置"
                >
                  <el-option
                    v-for="item in adPositionList"
                    :key="item.valueId"
                    :label="item.valueName"
                    :value="item.valueId"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item
              v-if="advertisingData.adRegionMode != 4"
              label="图片上传"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-upload
                ref="adPic"
                :disabled="advertisingData.adRegionMode == '' || isLook"
                class="avatar-uploader"
                :action="uploadUrl"
                :data="uploadData"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :on-error="uploadError"
                accept=".jpg, .png"
              >
                <img @click="clickPic(false)" v-if="advertisingData.adPic" :src="advertisingData.adPic" class="avatar" />
                <i
                  id="icon"
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  @click="clickPic(false)"
                ></i>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >建议尺寸：{{powerSize[advertisingData.adRegionMode-1]}}，图片支持jpg、png，图片大小不超过5m</div>
              </el-upload>
            </el-form-item>
            <el-form-item
              v-if="advertisingData.adRegionMode == 4"
              label="PC图片上传"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-upload
                ref="adPic"
                class="avatar-uploader"
                :action="uploadUrl"
                :data="uploadData"
                :disabled="isLook"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :on-error="uploadError"
                accept=".jpg, .png"
              >
                <img @click="clickPic(false)" v-if="advertisingData.adPic" :src="advertisingData.adPic" class="avatar" />
                <i
                  id="icon"
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  @click="clickPic(false)"
                ></i>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >建议尺寸：{{powerSize[advertisingData.adRegionMode-1]}}，图片支持jpg、png，图片大小不超过5m</div>
              </el-upload>
            </el-form-item>
            <el-form-item
              v-if="advertisingData.adRegionMode == 4"
              label="移动图片上传"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-upload
                ref="adPic"
                class="avatar-uploader"
                :action="uploadUrl"
                :data="uploadData"
                :disabled="isLook"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :on-error="uploadError"
                accept=".jpg, .png"
              >
                <img @click="clickPic(true)" v-if="advertisingData.adPic1" :src="advertisingData.adPic1" class="avatar" />
                <i
                  id="icon1"
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  @click="clickPic(true)"
                ></i>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >建议尺寸：{{powerSize[advertisingData.adRegionMode]}}，图片支持jpg、png，图片大小不超过5m</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="广告详情URL">
              <el-input
              :disabled="isLook"
                ref="contentLink"
                style="width:80%"
                clearable
                v-model="advertisingData.contentLink"
                maxlength="255"
                placeholder="请输入广告详情URL"
              ></el-input>
            </el-form-item>
            <el-form-item label="投放时间" :rules="[
      { required: true, message: ''}]">
              <el-date-picker
                style="width:80%"
                :disabled="isLook"
                v-model="advertisingData.useTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item
              v-if="advertisingData.adRegionMode >2"
              label="指定投放"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-radio-group :disabled="isLook" style="width:80%" v-model="advertisingData.campusPutMode">
                <el-radio
                  :label="item.value"
                  v-for="item in campusPutModeList"
                  :key="item.value"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="advertisingData.campusPutMode == 4"
              label="选择校区"
              :rules="[
      { required: true, message: ''}]"
            >
              <el-select
                ref="campusId"
                style="width:80%"
                v-model="advertisingData.campusSet"
                multiple
                :disabled="isLook"
                collapse-tags
                placeholder="请选择校区"
                @change="schoolChange"
              >
                <el-option
                  v-for="item in classList"
                  :key="item.campusId"
                  :label="item.name"
                  :value="item.campusId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div style="float:right;width:4rem;border-left:1px solid #e8e8e8;">
          <span class="launch_text">预览区域</span>
          <div class="preview_div" v-if="advertisingData.adRegionMode == 1">
            <div class="preview_show1"></div>
            <div
              class="preview_show1_replace"
              v-if="advertisingData.adPic"
              :style="{ background:replace_show}"
            ></div>
          </div>
          <div class="preview_div" v-else-if="advertisingData.adRegionMode == 2">
            <div class="preview_show2"></div>
            <div
              class="preview_show2_replace"
              v-if="advertisingData.adPic"
              :style="{ background:replace_show}"
            ></div>
          </div>
          <div class="preview_div" v-else-if="advertisingData.adRegionMode == 3">
            <div class="preview_show3"></div>
            <div
              class="preview_show3_replace"
              v-if="advertisingData.adPic"
              :style="{ background:replace_show}"
            ></div>
          </div>
          <div class="preview_div" v-else-if="advertisingData.adRegionMode == 4">
            <div class="preview_show4_1">
              <div
                class="preview_show4_replace"
                v-if="advertisingData.adPic"
                :style="{ background:replace_show}"
              ></div>
            </div>
            <div class="preview_show4_2">
              <div
                class="preview_show5_replace"
                v-if="advertisingData.adPic1"
                :style="{ background:replace_show1}"
              ></div>
            </div>
          </div>
        </div>
      </div>
      <div class="btn_div" style="width:6rem;" v-if="!isLook">
        <div class="btn_sure" @click="sure(1)">确定</div>
        <div class="btn_sure" @click="sure(2)">{{sure_title}}</div>
        <div class="btn_cancel" @click="cancel()">取 消</div>
      </div>
    </div>
  </div>
</template>

<script>
var vm;
var user;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      isAdd: true,
      isLook: false,
      isTwo: false,
      title: "",
      sure_title: "",
      replace_show: "",
      replace_show1: "",
      classList: [],
      uploadData: {
        content: "advertisinglogo"
      },
      adTerminalList: [],
      adRegionModeList: [],
      campusPutModeList: [],
      Fontsize: [
        "no-repeat center top /2rem 0.45rem",
        "no-repeat center top /1.76rem 2.4rem",
        "no-repeat center top /1.86rem 0.86rem",
        "no-repeat center top /2.45rem 0.45rem",
        "no-repeat center top /2rem 0.8rem"
      ],
      powerSize: ["1920x480", "1980x80", "710x280", "1562x350", "710x280"],
      adPositionList: [],
      advertisingData: {},
      uploadUrl: window.config.baseUrl + "file/upload",
      headers: {
        // 'Content-Type': 'multipart/form-data',
        token: tool.getItem(lsKey.token)
      }
    };
  },
  methods: {
    schoolChange(val) {},
    clickPic(isTwo) {
      console.log("clickPic",isTwo);
      vm.isTwo = isTwo;
    },
    handleCheckedChange(val) {
      console.log(val);
      vm.advertisingData.campusPutMode = val > 2 ? 1 : "";
      vm.advertisingData.adPic = "";
      api
        .adPostionList({
          areaId: val
        })
        .then(function(data) {
          if (data.result == "操作成功") {
            vm.advertisingData.adPositionId = "";
            vm.adPositionList = data.list;
          } else {
            tool.message({
              showClose: true,
              message: data.result,
              type: "warning"
            });
          }
        });
    },
    uploadError: function(response, file) {
      console.log("上传文件失败response" + response);
    },
    handleAvatarSuccess(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，" + res.data.result);
      } else {
        // vm.advertisingData.adPic = URL.createObjectURL(file.raw);
        if (vm.isTwo) {
          vm.advertisingData.adPic1 = res.data.url; //获取图片地址
          vm.replace_show1 =
            "url(" +
            vm.advertisingData.adPic1 +
            ") " +
            vm.Fontsize[vm.advertisingData.adRegionMode]; //根据选择的投放区域显示图片
        } else {
          vm.advertisingData.adPic = res.data.url; //获取图片地址
          vm.replace_show =
            "url(" +
            vm.advertisingData.adPic +
            ") " +
            vm.Fontsize[vm.advertisingData.adRegionMode - 1]; //根据选择的投放区域显示图片
        }
      }
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg" || "image/png"; //允许png图片
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        tool.message({
          showClose: true,
          message: "上传广告图片只能是 JPG/PNG 格式!",
          type: "warning"
        });
      }
      if (!isLt2M) {
        tool.message({
          showClose: true,
          message: "上传广告图片大小不能超过 5MB!",
          type: "warning"
        });
      }
      let fontSize;
      if (vm.isTwo) {
        fontSize = vm.powerSize[vm.advertisingData.adRegionMode];
      } else {
        fontSize = vm.powerSize[vm.advertisingData.adRegionMode - 1];
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = fontSize.split("x")[0];
        let height = fontSize.split("x")[1];
        console.log(width);
        console.log(height);
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
          let valid = image.width == width && image.height == height;
          valid ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          tool.message({
            showClose: true,
            message: "上传广告图片尺寸不符合，应为" + fontSize,
            type: "warning"
          });
          return Promise.reject();
        }
      );
      console.log(isSize);
      return isJPG && isLt2M;
      // return isJPG && isLt2M;
    },
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 11);
      let user = tool.getItem(lsKey.user, true); //得到当前用户信息
      //获取数据字典
      let dicdata = tool.getItem(lsKey.dict, true);
      if (data != null && data.adId != null) {
        vm.isAdd = false;
        vm.title =data.isLook ? "查看广告": "编辑广告";
        vm.sure_title = "编辑并上架";
        vm.isLook = data.isLook ? true : false;
        data.useTime = [data.useStartTime, data.useEndTime];
        data.adPic1 = "";
        vm.advertisingData = data;
        if (vm.advertisingData.adRegionMode == 4) {
          let picList = vm.advertisingData.adPic.split(",");
          vm.advertisingData.adPic = picList[0];
          vm.advertisingData.adPic1 =
            picList[0].substring(0, picList[0].lastIndexOf("/")) + picList[1];
          vm.replace_show1 =
            "url(" +
            vm.advertisingData.adPic1 +
            ") " +
            vm.Fontsize[vm.advertisingData.adRegionMode];
          vm.replace_show =
            "url(" +
            vm.advertisingData.adPic +
            ") " +
            vm.Fontsize[vm.advertisingData.adRegionMode - 1];
        } else {
          vm.replace_show =
            "url(" +
            vm.advertisingData.adPic +
            ") " +
            vm.Fontsize[vm.advertisingData.adRegionMode - 1];
        }
        api
          .adPostionList({
            areaId: vm.advertisingData.adRegionMode
          })
          .then(function(data) {
            if (data.result == "操作成功") {
              vm.adPositionList = data.list;
            } else {
              tool.message({
                showClose: true,
                message: data.result,
                type: "warning"
              });
            }
          });
      } else {
        vm.isAdd = true;
        vm.title = "新增广告";
        vm.sure_title = "新建并上架";
        vm.advertisingData = {
          adName: "",
          adPic: "",
          adPic1: "",
          contentLink: "",
          adRegionMode: "",
          adPositionId: "",
          campusPutMode: "",
          useStartTime: "",
          useEndTime: "",
          useTime: "",
          isDelete: "0",
          adStatusMode: 1,
          orgId: user.orgId,
          updateUserId: user.userId,
          useCount: 0,
          campusSet: [],
          adTerminalMode: 1
        };
      }
      api.adAreaList({}).then(function(data) {
        if (data.result == "操作成功") {
          vm.adRegionModeList = data.list;
        } else {
          tool.message({
            showClose: true,
            message: data.result,
            type: "warning"
          });
        }
      });
      var paras = {
        orgId: user.orgId + ""
      };
      api.campusListByOrg(paras).then(function(data) {
        if (data.result == "操作成功") {
          vm.classList = data.list;
        }
      });
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      //  vm.imgUrl = "";
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.isAdd = true;
        vm.advertisingData = {};
        vm.isLook = false;
      }, 500);
    },
    sure: function(val) {
      var rules = [];
      let adName = this.$refs.adName;
      let adRegionMode = this.$refs.adRegionMode;
      let adPosition = this.$refs.adPosition;
      let useStartTime = this.$refs.useStartTime;
      let useEndTime = this.$refs.useEndTime;
      let campusId = this.$refs.campusId;
      console.log(vm.advertisingData.useTime);

      rules.push({
        judge: tool.judge("classname", vm.advertisingData.adName),
        focus: adName,
        tips: "请输入正确的广告名称"
      });
      rules.push({
        judge: vm.advertisingData.adRegionMode,
        focus: adRegionMode,
        tips: "请选择投放区域"
      });
      rules.push({
        judge: vm.advertisingData.adPositionId,
        focus: adPosition,
        tips: "请选择投放位置"
      });
      rules.push({
        judge: vm.advertisingData.adPic,
        focus: $("#icon"),
        tips: "请选择广告图片"
      });
      // rules.push({
      //   judge: vm.advertisingData.useStartTime,
      //   focus: useStartTime,
      //   tips: "请选择投放开始时间"
      // });
      // rules.push({
      //   judge: vm.advertisingData.useEndTime,
      //   focus: useEndTime,
      //   tips: "请选择投结束时间"
      // });
      if (vm.advertisingData.campusPutMode == 4) {
        console.log(vm.advertisingData.campusSet);
        rules.push({
          judge: vm.advertisingData.campusSet.length != 0,
          focus: campusId,
          tips: "请选择指定投放校区"
        });
      }

      if (vm.advertisingData.useTime == "") {
        tool.message({
          showClose: true,
          message: "请选择投放时间",
          type: "warning"
        });
        return;
      } else {
        vm.advertisingData.useStartTime = vm.advertisingData.useTime[0];
        vm.advertisingData.useEndTime = vm.advertisingData.useTime[1];
      }
      let paras = tool.clone(vm.advertisingData);
      if (paras.adRegionMode == 4) {
        rules.push({
          judge: paras.adPic1,
          focus: $("#icon1"),
          tips: "请选择移动端广告图片"
        });
        paras.adPic =
          paras.adPic +
          "," +
          paras.adPic1.substr(paras.adPic1.lastIndexOf("/"));
        console.log(paras.adPic1.substring(0, paras.adPic1.lastIndexOf("/")));
        console.log(paras.adPic1.substr(paras.adPic1.lastIndexOf("/")));
      }
      if (!tool.validate(rules)) {
        return;
      }

      paras.adStatusMode = val;
      api.adAdd(paras).then(function(data) {
        if (data.resultCode == 2000) {
          if (vm.isAdd) {
            vm.$message({
              message: "添加成功",
              type: "success"
            });
          } else {
            vm.$message({
              message: "编辑成功",
              type: "success"
            });
          }
          vm.$emit("callback", "添加成功");
          vm.cancel();
        } else {
          vm.$message.error(data.message);
        }
      });
    }
  },
  created: function() {
    vm = this;
    user = tool.getItem(lsKey.user, true); //得到当前用户信息
    let dicdata = tool.getItem(lsKey.dict, true);
    this.campusPutModeList = dicdata["ad_campus_mode"]; //广告指定投放对象
    this.adTerminalList = dicdata["ad_terminal_mode"];
    console.log(this.campusPutModeList);
  }
};
</script>
<style scoped src="@/style/module/dialog.css"></style>
<style lang="scss">
#createAdvertising {
  .btn_div {
    padding: 0 0 0.3rem 0;
  }

  .panel {
    width: 12rem;
    padding-bottom: 0.2rem;
  }

  .ruleForm {
    padding-left: 0.5rem;
  }

  .el-radio-group {
    line-height: inherit;
  }

  .el-radio__label {
    font-size: 0.16rem;
    padding-left: 0.1rem;
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .grid-content {
    line-height: 0.5rem;
    text-align: center;
  }

  .launch_text {
    color: #999999;
    text-align: right;
    font-size: 0.14rem;
    margin-left: 0.3rem;
  }

  .preview_div {
    width: 100%;
    margin: 0 auto;
    position: relative;

    .preview_show1 {
      margin-left: 1rem;
      width: 2rem;
      height: 5.5rem;
      background: url(../../../assets/img/operation_manage/preview_show1.jpg)
        no-repeat center top / 2rem 5.5rem;
    }

    .preview_show1_replace {
      width: 2rem;
      height: 0.45rem;
      position: absolute;
      top: 0.08rem;
      left: 1rem;
    }

    .preview_show2 {
      margin-left: 0.7rem;
      width: 2.58rem;
      height: 5.61rem;
      background: url(../../../assets/img/operation_manage/preview_show3.png)
        no-repeat center top / 2.58rem 5.61rem;
    }

    .preview_show2_replace {
      width: 1.76rem;
      height: 2.4rem;
      position: absolute;
      top: 1.45rem;
      left: 1.15rem;
      background: url(../../../assets/img/operation_manage/defult_show.jpg)
        no-repeat center top / 1.76rem 2.4rem;
    }

    .preview_show3 {
      margin-left: 0.7rem;
      width: 2.58rem;
      height: 5.61rem;
      background: url(../../../assets/img/operation_manage/preview_show4.png)
        no-repeat center top / 2.58rem 5.61rem;
    }

    .preview_show3_replace {
      width: 1.86rem;
      height: 0.86rem;
      position: absolute;
      top: 1.93rem;
      left: 1.06rem;
      border-radius: 0.06rem;
      background: url(../../../assets/img/operation_manage/defult_show.jpg)
        no-repeat center top / 2rem 1.4rem;
    }

    .preview_show4_1 {
      margin-left: 0.5rem;
      width: 3rem;
      height: 1.35rem;
      position: relative;
      background: url(../../../assets/img/operation_manage/preview_show2.jpg)
        no-repeat center top / 3rem 1.35rem;

      .preview_show4_replace {
        width: 2.45rem;
        height: 0.45rem;
        position: absolute;
        top: 0.8rem;
        left: 0.48rem;
        background: url(../../../assets/img/operation_manage/defult_show.jpg)
          no-repeat center top / 2.5rem 0.45rem;
      }
    }

    .preview_show4_2 {
      margin-left: 0.5rem;
      margin-top: 0.2rem;
      position: relative;
      width: 2.58rem;
      height: 5.61rem;
      background: url(../../../assets/img/operation_manage/preview_show5.png)
        no-repeat center top / 2.58rem 5.61rem;

      .preview_show5_replace {
        width: 2rem;
        height: 0.8rem;
        position: absolute;
        top: 3.85rem;
        left: 0.3rem;
        border-radius: 0.06rem;
        background: url(../../../assets/img/operation_manage/defult_show.jpg)
          no-repeat center top / 2rem 0.8rem;
      }
    }
  }

  .avatar-uploader {
    .el-upload__tip {
      font-size: 0.12rem;
      color: #606266;
      margin-top: -0.2rem;
    }

    .el-upload {
      border: 1px dashed #8c939d;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 5.3rem;
      height: 1.1rem;
      line-height: 1.1rem;
      text-align: center;
    }

    .avatar {
      max-width: 5.3rem;
      height: 1.1rem;
      display: block;
      object-fit: cover;
    }
  }
}
</style>
